package com.sjtu.streetplan.net;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

import com.sjtu.streetplan.util.Position;

public class Net {

	public static final int HTTP_200 = 200;
	public static final String TAG_HTTPPOST = "HttpPost��ʽ";
	
	public static String positionList2JSON(List<Position> positions){
		JSONArray jsonResult = new JSONArray();
		for(Position position : positions){
			JSONObject jsonPosition = new JSONObject();
	        
			jsonPosition.put("user", position.getUser());
			jsonPosition.put("time", position.getTime().toString());
			jsonPosition.put("lon", position.getLon());
			jsonPosition.put("lat", position.getLat());
			jsonPosition.put("angle", position.getAngle());
			jsonResult.add(jsonPosition);
		}
		return jsonResult.toString();
	}
	
	// HttpPost��ʽ����
	public static void requestByHttpPost(String msg) throws Exception {
		String path = "http://202.120.58.146:808/adddot.php";
		// �½�HttpPost����
		HttpPost httpPost = new HttpPost(path);
		// Post����
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("data", msg));
		// �����ַ�
		HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
		// ���ò���ʵ��
		httpPost.setEntity(entity);
		// ��ȡHttpClient����
		HttpClient httpClient = new DefaultHttpClient();
		// ��ȡHttpResponseʵ��
		HttpResponse httpResp = httpClient.execute(httpPost);
		// �ж��ǹ�����ɹ�
		if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
			// ��ȡ���ص����
			String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
			Log.i(TAG_HTTPPOST, "HttpPost��ʽ����ɹ�������������£�");
			Log.i(TAG_HTTPPOST, result);
		} else {
			Log.i(TAG_HTTPPOST, "HttpPost��ʽ����ʧ��");
		}
	}
	
	public static void updateAllItems(List<Position> positions) throws Exception{
		String msg = positionList2JSON(positions);
		requestByHttpPost(msg);
	}
}
